// --------------------------------------------
// Last Modified: 12/22/2012
// By:administrator
// xSolon.STS - CustomSecurityTokenServiceConfiguration.cs
// --------------------------------------------

using System;
using System.IdentityModel.Configuration;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
using System.Web;

namespace xSolon.STS
{
    /// <summary>
    /// Extends the Microsoft.IdentityModel.Services.SecurityTokenServiceConfiguration class to 
    /// be consumed by the CustomSecurityTokenService.
    /// </summary>
    public class CustomSecurityTokenServiceConfiguration : SecurityTokenServiceConfiguration
    {
        static readonly object syncRoot = new object();

        static string CustomSecurityTokenServiceConfigurationKey = "CustomSecurityTokenServiceConfigurationKey";

        public CustomSecurityTokenServiceConfiguration() : base(Constants.IssuerName)
        {

            var signignCert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, Constants.SIGNING_CERTIFICATE_NAME);

            SigningCredentials = new X509SigningCredentials(signignCert);

            ServiceCertificate = signignCert;

            SecurityTokenService = typeof(xSolon.STS.CustomSecurityTokenService);

        }

        public static CustomSecurityTokenServiceConfiguration Current
        {
            get
            {
                HttpApplicationState httpAppState = HttpContext.Current.Application;

                CustomSecurityTokenServiceConfiguration myConfiguration = httpAppState.Get(CustomSecurityTokenServiceConfigurationKey) as CustomSecurityTokenServiceConfiguration;

                if (myConfiguration != null)
                {
                    return myConfiguration;
                }

                lock (syncRoot)
                {

                    myConfiguration = httpAppState.Get(CustomSecurityTokenServiceConfigurationKey) as CustomSecurityTokenServiceConfiguration;

                    if (myConfiguration == null)
                    {

                        myConfiguration = new CustomSecurityTokenServiceConfiguration();

                        httpAppState.Add(CustomSecurityTokenServiceConfigurationKey, myConfiguration);

                    }

                    return myConfiguration;
                }
            }
        }

    }
}